package com.ece.cart;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ece.CommandeBusinessControllerRemote;
import com.ece.beans.items.Item;
import com.ece.beans.users.Utilisateur;

/**
 * Servlet implementation class AddItemServlet
 */
public class SubmitCommandeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubmitCommandeServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Utilisateur user = (Utilisateur)request.getSession().getAttribute("user");
		List<Item> listItems = (List<Item>)request.getSession().getAttribute("cart");

		Context context;
		try {
			context = new InitialContext();
			CommandeBusinessControllerRemote cbc = (CommandeBusinessControllerRemote)context.lookup("CommandeBusinessController/remote");
			cbc.validerCommande(listItems, user);
			request.getSession().setAttribute("cart", new ArrayList<Item>());
			request.setAttribute("success", true);
		} catch (NamingException e) {
			e.printStackTrace();
			request.setAttribute("success", false);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("success", false);
		} finally {
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
	}

}
